package edu.ccut.saturn.authority.impl.login;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IParameterContext;

public class GetExtjsMenuList extends DefaultComponent {

	@SuppressWarnings("unchecked")
	@Override
	public void execute(IParameterContext parameterContext) throws Exception {
		List<Map<String, String>> menuList = (List<Map<String, String>>)parameterContext.getParameterValue(0);

		parameterContext.setParameter(1, generateExtjsTreeList(menuList));
	}

	private List<Map<String, Object>> generateExtjsTreeList(
			List<Map<String, String>> tree) {
		
		List<Map<String, String>> rootNodes = getChildrenTreeNodeById("", tree);

		List<Map<String, Object>> jsonTree = new ArrayList<Map<String, Object>>();
		LinkedList<Map<String, Object>> queue = new LinkedList<Map<String, Object>>();

		for (Map<String, String> root : rootNodes) {
			Map<String, Object> extjsRoot = this.createExtjsTreeNode(root);
			queue.add(extjsRoot);
			jsonTree.add(extjsRoot);
		}

		while (!queue.isEmpty()) {
			Map<String, Object> node = queue.removeLast();

			List<Map<String, String>> children = this.getChildrenTreeNodeById(
					(String)node.get("id"), tree);
			
			for (Map<String, String> child : children) {
				Map<String, Object> extjsChild = this.createExtjsTreeNode(child);
				
				this.addExtjsTreeChildNode(node, extjsChild);
				queue.add(extjsChild);
			}
		}
		
		return jsonTree;
	}

	private List<Map<String, String>> getChildrenTreeNodeById(String id,
			List<Map<String, String>> allNodes) {
		List<Map<String, String>> nodes = new ArrayList<Map<String, String>>();

		for (Map<String, String> node : allNodes) {
			if (id.equals(node.get("parentId"))) {
				nodes.add(node);
			}
		}

		return nodes;
	}

	private Map<String, Object> createExtjsTreeNode(Map<String, String> oldNode) {
		String id = oldNode.get("id");
		String parentId = oldNode.get("parentId");
		String path = oldNode.get("path");
		String icon = oldNode.get("icon");
		String label = oldNode.get("label");

		Map<String, Object> node = new HashMap<String, Object>();

		node.put("id", id);
		node.put("text", label);
		node.put("path", path);
		node.put("icon", icon);
		node.put("parentId", parentId);
		node.put("allowDrag", false);
		node.put("leaf", true);

		return node;
	}

	@SuppressWarnings("unchecked")
	private void addExtjsTreeChildNode(Map<String, Object> node,
			Map<String, Object> child) {
		
		List<Map<String, Object>> children = (List<Map<String, Object>>) node.get("children");
		if (children == null) {
			children = new ArrayList<Map<String,Object>>();
			node.put("children", children);
			node.put("leaf", false);
		}
		
		children.add(child);
	}
}